package com.fzk.server;

import com.fzk.log.Logger;
import com.fzk.exception.MyException;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

/**
 * 错误处理居然是个入站事件
 *
 * @author fzk
 * @date 2023-03-19 18:18
 */
public class ExceptionHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws MyException {
        Logger.error(String.format("消息类型: %s 没有对应的handler处理?", o.getClass()));
        throw new MyException(1, String.format("消息类型: %s 没有对应的handler处理?", o.getClass()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
        Logger.error("ExceptionHandler handle error " + e.getMessage(), e);
        if (ctx.channel().isActive()) {
//            HttpResponseUtil.sendError(ctx, request, HttpResponseStatus.INTERNAL_SERVER_ERROR);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.copiedBuffer(e.toString(), StandardCharsets.UTF_8));
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
            HttpUtil.setContentLength(response, response.content().readableBytes());
            HttpUtil.setKeepAlive(response, false);// 出现异常还是关闭连接吧
            ctx.writeAndFlush(response);
        }
    }
}
